package pc.nick.server;

import pc.nick.http.HttpServletRequest;
import pc.nick.http.HttpServletResponse;
import pc.nick.server.process.DynamicProcessor;
import pc.nick.server.process.Processor;
import pc.nick.server.process.StaticProcessor;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/**
 * ServerService: 线程请求处理类
 * 构造的参数传过来一个socket.
 * 1.对客户端收到的流数据进行解析与封装，得到request对象
 * 2.根据流数据与request对象得到response对象
 * 3.对静态请求与动态请求分开处理，完善响应对象
 * 4.关闭连接
 */
public class ThreadTask implements Runnable{

    private Socket socket;
    public ThreadTask(Socket socket) {

        this.socket = socket;
    }

    @Override
    public void run() {
        System.out.println("一个任务 正在由线程 " + Thread.currentThread().getName() + " 执行。");
        InputStream iis = null;
        OutputStream oos = null;
        try {
            iis = socket.getInputStream();
            oos = socket.getOutputStream();
        }catch (IOException e){
            e.printStackTrace();
            System.out.println("客户端" + this.socket.getRemoteSocketAddress() + "掉线");
        }

        // http是一个基于请求与响应的协议
        HttpServletRequest request = new HttpServletRequest(iis);
        HttpServletResponse response = new HttpServletResponse(request, oos);
        String url = request.getRequestURI();

        // 判断是动态的还是静态的请求
        Processor processor;
        if(url.indexOf(".action") > 0){ // 此处简化了，以为action结尾的为动态请求
            processor = new DynamicProcessor();
        }else{
            processor = new StaticProcessor();
        }
        processor.process(request, response);

        try {
            // http是无状态的短连接
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
